/*
 * Copyright (C) 2003-2011 eXo Platform SAS.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see<http://www.gnu.org/licenses/>.
 */
package khiem.demo.jscompress.libs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import com.google.javascript.jscomp.WarningLevel;

import khiem.demo.jscompress.BaseCompressor;
import khiem.demo.jscompress.ResourceType;

/**
 * Created by The eXo Platform SAS
 * Author : eXoPlatform
 *          exo@exoplatform.com
 * Jul 14, 2011  
 */
public class ClosureCompiler extends BaseCompressor {
  
  private static ClosureCompiler instance;
  
  static {
    instance = new ClosureCompiler();
  }
  
  public static ClosureCompiler getInstance() {
    return instance;
  }
  
  private ClosureCompiler() {}
  

  /* (non-Javadoc)
   * @see khiem.demo.jscompress.BaseCompressor#compress(java.io.Reader, java.io.Writer)
   */
  @Override
  public void compress(Reader in, Writer out) {
    CompilationLevel level = CompilationLevel.SIMPLE_OPTIMIZATIONS;
    //
    Compiler compiler = new Compiler();
    CompilerOptions options = new CompilerOptions();
    level.setOptionsForCompilationLevel(options);
    WarningLevel.QUIET.setOptionsForWarningLevel(options);
    JSSourceFile extern = JSSourceFile.fromCode("extern", "");

    //
    JSSourceFile jsInput;
    try {
       String code = JSSourceFile.fromReader("code", in).getCode();
       jsInput = JSSourceFile.fromCode("jsInput", code);
       compiler.compile(extern, jsInput, options);
       out.write(compiler.toSource());
    }
    catch (Exception ex) {
       ex.printStackTrace();
    }
  }

  /* (non-Javadoc)
   * @see khiem.demo.jscompress.BaseCompressor#getType()
   */
  @Override
  public ResourceType getType() {
    return ResourceType.JS;
  }
  
  
  /**
   * Compresses Javascript code via remote service from closure-compiler appspot
   * @param in
   * @param out
   * @throws IOException
   */
  public void remoteCompress(Reader in, Writer out) throws IOException {
    // prepare parameters
    String closure_url = "http://closure-compiler.appspot.com/compile";
    String closure_params = "compilation_level=SIMPLE_OPTIMIZATIONS&output_format=text&output_info=compiled_code";
    // String closure_params = "compilation_level=ADVANCED_OPTIMIZATIONS&output_format=text&output_info=compiled_code";
    
    // read input
    BufferedReader buffer = new BufferedReader(in);
    // read the input javascript code
    StringBuilder js_code = new StringBuilder();
    String line;
    while ((line = buffer.readLine()) != null) {
      js_code.append(line);
      js_code.append("\n");
    }
    buffer.close();
    closure_params += "&js_code=" + URLEncoder.encode(js_code.toString(), "UTF-8");
    
    // send POST request
    StringBuilder answer = new StringBuilder();
    try {
      URL url = new URL(closure_url);
      HttpURLConnection con = (HttpURLConnection) url.openConnection();
      con.setRequestMethod("POST");
      con.setDoOutput(true);
      con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      con.setUseCaches(false);
      OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
      writer.write(closure_params);
      writer.flush();
      
      BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
      while ((line = reader.readLine()) != null) {
          answer.append(line);
      }
      writer.close();
      reader.close();
      
      //Output the response
      System.out.println(answer.toString());
      
    } catch (Exception e) {
      e.printStackTrace();
    }
    
    // write to output
    out.write(answer.toString());
  }

}
